from django.http import HttpResponse
from django.core.serializers import serialize

from ...models.chat_items import ChatItems
from ...models.chat_history import ChatHistory
from ...models.chat_roles import ChatRoles
from ...utils.users import get_login_user_id
from ...utils.time_conversion import iso_to_times
from ...utils.data_handle import calc_tokens


import json


def chats_list(request):
    '''
    列出所有的会话
    get
    '''
    userid = get_login_user_id(request, isadmin=False)
    if not userid:
        res_mes = {
            "code": 0,
            "data": []
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

    all_chatitems = ChatItems.objects.filter(user_id=userid).order_by('-created_at')

    json_data_str = serialize('json', all_chatitems)
    json_data = json.loads(json_data_str)

    data = []
    for i in range(len(json_data)):
        json_data[i]['fields']['id'] = json_data[i]['pk']

        # 数据处理
        created_at_second = iso_to_times(json_data[i]['fields']['created_at'])
        updated_at_second = iso_to_times(json_data[i]['fields']['updated_at'])
        json_data[i]['fields']['created_at'] = created_at_second
        json_data[i]['fields']['updated_at'] = updated_at_second

        del json_data[i]['fields']['deleted_at']

        # 获取角色头像
        role_id = json_data[i]['fields']['role_id']
        role_obj = ChatRoles.objects.filter(id=role_id)
        if role_obj:
            json_data[i]['fields']['icon'] = role_obj[0].icon

        data.append(json_data[i]['fields'])


    res_mes = {
        "code": 0,
        "data": data
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def chats_detail(request):
    # 导出占位
    res_mes = {
        "code": 0,
        "data": []
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def chats_update(request):
    '''
    更新会话标题
    POST
    re = {
        "chat_id": "71ccc06a-4ac3-4d69-aea5-968ec3eab27b",
        "title": "qqq"
    }
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        try:
            ChatItems.objects.filter(chat_id=json_obj['chat_id']).update(title=json_obj['title'])
        except:
            res_mes = {
                "code": 1,
                "message": "Failed to update database"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

        res_mes = {
            "code": 0,
            "data": "Success"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def chats_remove(request):
    '''
    删除会话
    get
    '''
    chat_id = request.GET.get('chat_id')

    if not chat_id:
        res_mes = {
            "code": 1,
            "data": "非法参数或参数解析失败"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

    userid = get_login_user_id(request, isadmin=False)

    try:
        del_obj = ChatItems.objects.filter(user_id=userid, chat_id=chat_id)
        del_obj.delete()
    except:
        res_mes = {
            "code": 1,
            "message": "Failed to remove chat from database."
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

    res_mes = {
        "code": 0,
        "data": "Success"
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def chats_history(request):
    '''
    会话历史
    get
    '''
    chat_id = request.GET.get('chat_id')

    try:
        all_chathistory = ChatHistory.objects.filter(chat_id=chat_id)
    except:
        res_mes = {
            "code": 1,
            "message": "No history message."
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

    json_data_str = serialize('json', all_chathistory)
    json_data = json.loads(json_data_str)

    data = []
    for i in range(len(json_data)):
        json_data[i]['fields']['id'] = json_data[i]['pk']

        # 数据处理
        created_at_second = iso_to_times(json_data[i]['fields']['created_at'])
        updated_at_second = iso_to_times(json_data[i]['fields']['updated_at'])
        json_data[i]['fields']['created_at'] = created_at_second
        json_data[i]['fields']['updated_at'] = updated_at_second

        del json_data[i]['fields']['deleted_at']

        data.append(json_data[i]['fields'])

    res_mes = {
        "code": 0,
        "data": data
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def chats_clear(request):
    '''
    清理用户的所有会话
    get
    '''
    userid = get_login_user_id(request, isadmin=False)
    if not userid:
        res_mes = {
            "code": 400,
            "data": "Not Authorized"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

    all_chatitems = ChatItems.objects.filter(user_id=userid)
    json_data_str = serialize('json', all_chatitems)
    json_data = json.loads(json_data_str)

    all_chatid_data = []
    for i in range(len(json_data)):
        all_chatid_data.append(json_data[i]['fields']['chat_id'])

    try:
        ChatHistory.objects.filter(user_id=userid, chat_id__in=all_chatid_data).delete()
        all_chatitems.delete()
    except:
        res_mes = {
            "code": 1,
            "data": "Failed to remove chat from database."
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

    res_mes = {
        "code": 0,
        "data": "Success"
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def chats_tokens(request):
    '''
    统计 token 数量
    POST
    re = {
        "text": "",
        "model": "gpt-4-0125-preview",
        "chat_id": "47669226-f525-4253-82eb-45406b2a1ec2"
    }
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        # 先获取用户id
        userid = get_login_user_id(request, isadmin=False)
        if not userid:
            res_mes = {
                "code": 400,
                "data": "Not Authorized"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

        # 如果没有传入 text 字段，则说明是获取当前 reply 总的 token 消耗（带上下文）
        if not json_obj['text'] and json_obj['chat_id']:
            last_chathistory = ChatHistory.objects.filter(user_id=userid, chat_id=json_obj['chat_id'], type="reply").last()
            if last_chathistory:
                res_mes = {
                    "code": 0,
                    "data": last_chathistory.tokens
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
            else:
                res_mes = {
                    "code": 1,
                    "data": 0
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)

        tokens = calc_tokens(json_obj['text'], json_obj['model'])

        res_mes = {
            "code": 0,
            "data": tokens
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def chats_stop(request):
    # 返回数据
    from django.core.cache import cache
    userid = get_login_user_id(request ,isadmin=False)
    cache.set(f'huihua-{userid}', True)


    res_mes = {
        "code": 0,
        "data": []
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)

